/**
 * @author liangxi
 * @since 2023/12/21
 */

#ifndef DESIGNPATTERN_SINGLETON4_H
#define DESIGNPATTERN_SINGLETON4_H

#include <mutex>

namespace Singleton {

    /**
     * 懒汉式，通过std::call_one保证线程安全(C++11以上)
     */
    class [[maybe_unused]] Singleton4 {
    public:
        [[maybe_unused]] static Singleton4 *getInstance() {
            static Singleton4 *instance = nullptr;
            static std::once_flag flag;

            //确保instance = new Singleton4();只会被执行一次
            std::call_once(flag, [] {
                instance = new Singleton4();
            });
            return instance;
        }

    private:
        Singleton4() = default;

        Singleton4(const Singleton4 &rhs) = default;

    };

} // Singleton

#endif //DESIGNPATTERN_SINGLETON4_H
